package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.SpotComment;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.SpotCommentQuery;
import cn.wolfcode.luowowo.comment.repository.SpotCommentRepository;
import cn.wolfcode.luowowo.comment.service.ISpotCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class SpotCommentServiceImpl implements ISpotCommentService {
    @Autowired
    private SpotCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public SpotComment saveOrUpdate(SpotComment spotComment) {
        spotComment.setTime(new Date());
        if (spotComment.getType() == TravelComment.TRAVLE_COMMENT_TYPE) {
            SpotComment respotComment = repository.findById(spotComment.getSpotComment().getId()).get();
            spotComment.setSpotComment(respotComment);

        }
        repository.save(spotComment);
        return spotComment;
    }

    @Override
    public Page<SpotComment> query(SpotCommentQuery qo) {
        Query query = new Query();
        query.addCriteria(Criteria.where("spotId").is(qo.getSpotId()));
        //根据query 这个条件去查满足条件的数量
        long total = template.count(query, SpotComment.class);
        if (total == 0) {
            return Page.empty();
        }
        //查list
        //添加分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageable);
        List<SpotComment> spotComments = template.find(query, SpotComment.class);
        return new PageImpl<>(spotComments, pageable, total);
    }

    @Override
    public long getCount(Long spotId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("spotId").is(spotId));
        //查count
        long count = template.count(query, SpotComment.class);
        return count;
    }

    @Override
    public List<SpotComment> selectNewCommentTop10() {
        Query query = new Query();
        query.skip( 0 ).limit( 10 );
        query.with( Sort.by( Sort.Direction.DESC, "time" ) );
        List <SpotComment> spotComments = template.find( query, SpotComment.class );
        return spotComments;
    }
}
